<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/4/13
 * Time: 下午7:29
 */

namespace app\admin\controller;

use app\admin\model;

class AuthManager extends Admin
{
    /**
     * @var string
     */
    protected $templatePrefix = 'admin/authmanager/';

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new model\AuthGroup();
    }

    /**
     * 用户组首页
     * @return mixed
     */
    public function index()
    {
        //  获取用户所在的用户组
        $authGroupAccess = new model\AuthGroupAccess();
        $groupList = $authGroupAccess->getGroupIdsByAdminId(ADMIN_UID);
        $list = $this->model->where(['id'=>['not in', $groupList]])->where('status', 99)->order('id', 'DESC')->select();

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->fetch('index', ['list'=>$list]);
    }

    /**
     *
     */
    public function add()
    {
        $info = $this->model;
        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 更新菜单页面
     * @return mixed
     */
    public function edit()
    {
        $id = input('param.id');

        if (empty($id)) {
            $this->error('缺少必要参数', cookie('__forward__'));
        }

        $info = $this->model->get($id);

        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 保存数据
     */
    public function save()
    {
        if (!request()->isPost()) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $id = input('post.id', 0);

        if (empty($id)) {
            $_POST['rules'] = '';
            $re = $this->model->data($_POST)->allowField(true)->save();
        } else {
            $re = $this->model->allowField(true)->save($_POST, ['id' => $id]);
        }

        if ($re === false) {
            $this->error('操作失败');
        }

        $this->success('操作成功', cookie('__forward__'));
    }

    /**
     *
     */
    public function access()
    {
        $groupId = input('groupid', 0);

        if (empty($groupId)) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $authRule = new model\AuthRule();

        if (request()->isPost()) {

            $rule = $_POST['rule'];

            $ruleIds = [];

            foreach ($rule as $key=>$value) {
                if (!isset($value['type']) || !isset($value['name'])) {
                    continue;
                }

                $ruleIds[$key] = $authRule->getRuleIdByNameType($value['name'], $value['type']);
            }

            $data['rules'] = arr2str($ruleIds);
            $re = $this->model->allowField(true)->save($data, ['id' => $groupId]);
            if ($re !== false) {
                $this->success('操作成功');
            }
            $this->error('操作失败');
        }

        $info = $this->model->find($groupId);

        $ruleList = $authRule->where(['id'=>['in', $info->rules]])->select();

        $rules = [];
        foreach ($ruleList as $key=>$value) {
            $rules[$key] = $value->name;
        }

        //  获取菜单节点
        $mainMenuList = $this->getMainMenuList();

        $sidebarMenuList = [];
        foreach ($mainMenuList as $key=>$value) {
            $list = $this->getSidebarMenuList($value['id']);
            $sidebarMenuList[$value['id']] = list_to_tree($list, 'id', 'pid', '_child', $value['id']);
        }

        $mainMenuList = list_to_tree($mainMenuList);

        $model = new model\AdminMenu();

        $buttonMenuList =  $model->getUseList(3);

        return $this->fetch('access', ['info'=>$info, 'mainMenuList'=>$mainMenuList, 'sidebarMenuList'=>$sidebarMenuList, 'buttonMenuList'=>$buttonMenuList, 'rules'=>$rules]);
    }


    /**
     * 成员授权
     * @return mixed
     */
    public function userAccess()
    {
        $groupId = input('groupid', 0);

        if (empty($groupId)) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $model = new model\AuthGroupAccess();

        $list = $model->getGroupAccessUser($groupId);

        return $this->fetch('user_access', ['list'=>$list, 'groupId'=>$groupId]);
    }

    /**
     * 添加成员授权
     */
    public function addGroupAccess()
    {
        $groupId = input('groupid', 0);

        $adminIds = input('adminids', 0);

        if (empty($groupId) || empty($adminIds)) {
            $this->error('参数错误');
        }

        $adminMember = new model\AdminMember();
        $model = new model\AuthGroupAccess();
        foreach (str2arr($adminIds) as $key=>$adminId) {
            if (!$adminMember->find($adminId)) {
                $this->error('不存在编号为：'.$adminId.'的后台管理员');
            }
            $re = $model->where('group_id', $groupId)->where('admin_id', $adminId)->find();
            if (!$re) {
                $model->insert([
                    'group_id' => $groupId,
                    'admin_id' => $adminId
                ]);
            }
        }

        $this->success('操作成功');
    }

    /**
     * 删除成员授权
     */
    public function delGroupAccess()
    {
        $groupId = input('groupid', 0);

        $adminIds = input('adminids', 0);

        if (empty($groupId) || empty($adminIds)) {
            $this->error('参数错误');
        }

        if (is_array($adminIds)) {
            $adminIds = arr2str($adminIds);
        }


        $model = new model\AuthGroupAccess();
        $re = $model->where('group_id', $groupId)->where(['admin_id'=>['in', $adminIds]])->delete();

        if ($re === false) {
            $this->error('操作失败');
        }

        $this->success('操作成功');
    }

}